package com.anyonavinfo.cpaddemo.service.musicplayerservice;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;
import com.anyonavinfo.cpaddemo.Application;

import static android.content.Context.BIND_AUTO_CREATE;

/**
 * Created by ZuiC on 2017/2/1.
 */

public class MusicServiceManager implements IMusicService{

    private Context mContext;
    private static MusicServiceManager INSTANCE = null;
    private PlayMusicService musicService;
    private MyMusicConnection musicConn;
    private String TAG = "MusicLog";

    public static MusicServiceManager getInstance(){
        if (INSTANCE == null) {
            INSTANCE = new MusicServiceManager();
        }
        return INSTANCE;
    }

    private MusicServiceManager(){
        mContext = Application.getContextObject();
        bindService();
    }

    private void bindService() {
        Intent musicIntent=new Intent(mContext, PlayMusicService.class);
        musicConn= new MyMusicConnection();
        mContext.bindService(musicIntent,musicConn,BIND_AUTO_CREATE);
        Log.i(TAG, "bindService: ");
    }


    public void endService() {
        if (musicConn != null) {
            mContext.unbindService(musicConn);
        }
        Log.i(TAG, "endService: ");
    }

    @Override
    public void play() {
        Log.i(TAG, "play: MusicServiceManager");
        musicService.play();
    }

    @Override
    public void play(int index) {
        musicService.play(index);
    }

    @Override
    public void pause() {
        musicService.pause();
    }

    @Override
    public void previous() {
        musicService.previous();
    }

    @Override
    public void next() {
        musicService.next();

    }

    @Override
    public void playRandom() {

    }

    @Override
    public int getCurrentPosition() {
        return musicService.getCurrentPosition();
    }

    @Override
    public void stop() {
        musicService.stop();
    }

    @Override
    public boolean isPlaying() {
        return musicService.isPlaying();
    }

    private class MyMusicConnection implements ServiceConnection{
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            musicService=((PlayMusicService.MyBinder) iBinder).getService();
        }
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            musicService=null;
        }
    }
}
